package cn.bytecollege.controller;

import cn.bytecollege.model.Evaluation;
import cn.bytecollege.model.Goods;
import cn.bytecollege.model.User;
import cn.bytecollege.service.EvaluationService;
import cn.bytecollege.service.GoodsService;
import cn.bytecollege.service.UserService;
import cn.bytecollege.vo.EvaluationVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/goods")
@Log4j2
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private UserService userService;
    @Autowired
    private EvaluationService evaluationService;
    /**
     * 商品详情页面
     * @param goodsId
     * @param model
     * @return
     */
    @GetMapping("/goodsDetail")
    public String goodsDetail(Integer goodsId,
                              Model model) {
        Goods goods = goodsService.getById(goodsId);
        model.addAttribute("goods", goods);
        List<Evaluation> evaluationListById = goodsService.getEvaluationById(goodsId);
        List<EvaluationVO> evaluationVOList = new ArrayList<>();
        for (Evaluation evaluation : evaluationListById) {

            EvaluationVO evaluationVO = new EvaluationVO();
            BeanUtils.copyProperties(evaluation,evaluationVO);
            evaluationVO.setUser(userService.getUserById(evaluationVO.getUserId()));
            evaluationVOList.add(evaluationVO);
        }
        model.addAttribute("evaluationVOList",evaluationVOList);
        return "productDetail";
    }


    @RequestMapping("/getGoodsLikeName")
    public String getGoodsLikeName(String goodsName,
                                 Model model) {
        log.info(goodsName);
        model.addAttribute("goodsList",goodsService.getLikeName(goodsName));
        return "search";
    }

    @PostMapping("/addEvaluation")

    public String addEvaluation(EvaluationVO evaluationVO,
                                HttpSession session) {
        Evaluation evaluation = new Evaluation();
        BeanUtils.copyProperties(evaluationVO, evaluation);
//        User user = (User) session.getAttribute("user");
//        evaluation.setUserId(user.getUserId());
        evaluation.setUserId(3);

        log.info(evaluation.toString());
        evaluationService.addEvaluation(evaluation);
        return "redirect:/goods/goodsDetail?goodsId="+evaluationVO.getGoodsId();
    }

}
